<template>
  <div class="goodsBaseInfo">
    <el-card>
      <template #header>
        <el-icon><Goods /></el-icon>
        <span>商品基本信息</span>
      </template>
      <template #default>
        <el-form class="custom_form" ref="formRef" :model="form" :rules="rules" size="large" label-width="230">
          <el-form-item label="厂商" prop="merchantId" required>
            <el-select
              class="input-w"
              v-model="form.merchantId"
              filterable
              remote
              remote-show-suffix 
              clearable 
              placeholder="请输入厂商名称查询"
              :remote-method="loadMembers"
              :loading="loading"
              @change="loadTransport">
              <el-option v-for="item in members" :key="item.merchantId" :label="item.merchantName" :value="item.merchantId"/>
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称" prop="name" required>
            <el-input v-model="form.name" type="text" placeholder="请输入商品名称" clearable class="input-y"></el-input>
          </el-form-item>
          <el-form-item label="商品货号" prop="productSn" required>
            <el-input v-model="form.productSn" type="text" placeholder="请输入商品货号" clearable class="input-w"></el-input>
          </el-form-item>
          <el-form-item label="副标题" prop="subTitle" required>
            <el-input v-model="form.subTitle" type="text" placeholder="请输入副标题" clearable class="input-y"></el-input>
          </el-form-item>
          <el-form-item label-width="0">
            <el-form-item label="商品分类" prop="parentCategoryId" required>
              <el-select v-model="form.parentCategoryId" placeholder="请选择商品Ⅰ级分类" clearable class="input-w" @change="loadGoodsType">
                <el-option v-for="item in goodTypesOne" :key="item.productCategoryId" :label="item.name" :value="item.productCategoryId"/>
              </el-select>
            </el-form-item>
            <el-form-item prop="subCategoryId" required label-width="20">
              <el-select v-model="form.subCategoryId" placeholder="请选择商品Ⅱ级分类" clearable class="input-w" @change="goodTypesTwoChange">
                <el-option v-for="item in goodTypesTwo" :key="item.productCategoryId" :label="item.name" :value="item.productCategoryId"/>
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item label="品牌" prop="brandId" required>
            <el-select
              class="input-w"
              v-model="form.brandId"
              filterable
              remote
              remote-show-suffix 
              clearable 
              placeholder="请输入品牌名称查询"
              :remote-method="loadBrands"
              :loading="loading" 
              @change="brandChange">
              <el-option v-for="item in brands" :key="item.brandId" :label="item.name" :value="item.brandId"/>
            </el-select>
          </el-form-item>
          <el-form-item label="商品主图" prop="pic" required>
            <img-cutter v-model="form.pic" :multiple="false" :isCard="true" width="250" height="150"></img-cutter>
          </el-form-item>
          <el-form-item label="轮播图片" prop="carouselPic" required>
            <img-cutter v-model="form.carouselPic" :isCard="true" width="250" height="150"></img-cutter>
          </el-form-item>
          <el-form-item label="出厂价" prop="oriPrice" required>
            <el-input v-model="form.oriPrice" type="number" placeholder="请输入出厂价" clearable class="input-w">
              <template #prefix>
                <span>￥</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="销售价格" prop="salePrice" required>
            <el-input v-model="form.salePrice" type="number" placeholder="请输入销售价格" clearable class="input-w">
              <template #prefix>
                <span>￥</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="赠送积分" prop="giftPoint" required>
            <el-input v-model="form.giftPoint" type="number" placeholder="请输入赠送积分" clearable class="input-w"></el-input>
          </el-form-item>
          <el-form-item label="单位" prop="unit" required>
            <el-input v-model="form.unit" type="text" placeholder="请输入单位" clearable class="input-w"></el-input>
          </el-form-item>
          <el-form-item label="商品服务" prop="serviceChoose" required>
            <el-select
              class="input-w"
              v-model="form.serviceChoose"
              multiple
              clearable 
              placeholder="请选择商品服务"
              @change="goodsServiceChange">
              <el-option v-for="item in goodServices" :key="item.serviceId" :label="item.serviceName" :value="item.serviceId"/>
            </el-select>
          </el-form-item>
          <el-form-item label="商品标签" prop="labelIdList" required>
            <el-select
              class="input-w"
              v-model="form.labelIdList"
              multiple
              clearable 
              placeholder="请选择商品标签">
              <el-option v-for="item in labelList" :key="item.labelId" :label="item.labelName" :value="item.labelId"/>
            </el-select>
          </el-form-item>
          <el-form-item label="运费模板" prop="transportId" required>
            <el-select
              class="input-w"
              v-model="form.transportId"
              clearable 
              placeholder="请选择商品服务">
              <el-option v-for="item in transports" :key="item.transportId" :label="item.transportName" :value="item.transportId"/>
            </el-select>
          </el-form-item>
          <el-form-item label="商品详情" prop="detailsMobileHtml">
            <tinymce-editor v-model="form.detailsMobileHtml" ref="editorRef"></tinymce-editor>
          </el-form-item>
        </el-form>
        <div class="btns">
          <el-button size="large" @click="doClose">返回</el-button>
          <el-button type="primary" size="large" @click="doNextStep">下一步</el-button>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup name="goodsBaseInfo">
  import { 
    // getFactoryListApi, 
    getGoodsTypeListApi, 
    getBrandListApi, 
    saveOrUpdateGoodsBaseInfoApi, 
    getGoodsBaseInfoApi, 
    getGoodsServiceListApi, 
    getFreightTempListApi, 
    // getGoodsLabelListApi
  } from '@/api/api'
  import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
  import { useStore } from 'vuex' 

  const store = useStore()

  const currentThis = getCurrentInstance().appContext.config.globalProperties
  // 定义传值给父组件数据方法
  const emits = defineEmits(['nextStep', 'close'])
  defineExpose({init, clearEditor}) // 抛出组件方法供父组件使用

  const formRef = ref(null)
  const editorRef = ref(null)
  
  const  currentData = reactive({
    loading: false,
    members: [],
    goodTypesOne: [],
    goodTypesTwo: [],
    brands: [],
    goodServices: [],
    transports: [],
    labelList: [],
    form: {
      productId: '',
      merchantId: '',
      name: '',
      productSn: '',
      subTitle: '',
      parentCategoryId: '',
      subCategoryId: '',
      brandId: '',
      pic: '',
      carouselPic: '',
      oriPrice: '',
      salePrice: '',
      giftPoint: '',
      unit: '',
      serviceIds: '',
      labelIdList: [],
      detailsMobileHtml: '',
      parentCategoryName: '',
      subCategoryName: '',
      brandName: '',
      serviceChoose: [],
      transportId: '',
      productType: 0
    },
    rules: {
      merchantId: [{ required: true, message: '请选择厂商', trigger: ['blur', 'change'] }],
      name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
      productSn: [{ required: true, message: '请输入商品货号', trigger: 'blur' }],
      subTitle: [{ required: true, message: '请输入副标题', trigger: 'blur' }],
      parentCategoryId: [{ required: true, message: '请选择商品Ⅰ级分类', trigger: 'blur' }],
      subCategoryId: [{ required: true, message: '请选择商品Ⅱ级分类', trigger: 'blur' }],
      brandId: [{ required: true, message: '请选择品牌', trigger: 'blur' }],
      pic: [{ required: true, message: '请上传商品主图', trigger: 'blur' }],
      carouselPic: [{ required: true, message: '请上传轮播图', trigger: 'blur' }],
      oriPrice: [{ required: true, message: '请输入出厂价', trigger: 'blur' }],
      salePrice: [{ required: true, message: '请输入销售价格', trigger: 'blur' }],
      giftPoint: [{ required: true, message: '请输入赠送积分', trigger: 'blur' }],
      unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
      transportId: [{ required: true, message: '请选择运费模板', trigger: 'blur' }],
      labelIdList: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value.length) {
              callback(new Error('请选择商品标签'))
            } else  {
              callback()
            }
          } 
        }
      ],
      serviceChoose: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value.length) {
              callback(new Error('请选择商品服务'))
            } else  {
              callback()
            }
          } 
        }
      ],
      detailsMobileHtml: [{ required: true, message: '请输入商品详情', trigger: 'blur' }]
    }
  })
  let {loading, members, goodTypesOne, goodTypesTwo, brands, goodServices, transports, labelList, form, rules} = toRefs(currentData)

  // 初始化数据
  init()
  function init() {
    currentData.form.productId = store.state.productId
    if(currentData.form.productId) {
      getGoodsBaseInfoApi(currentData.form.productId).then(res => {
        if(res.code === '200') {
          currentData.form = res.data
          let serviceChoose = []
          for (const key in res.data.serviceMap) {
            serviceChoose.push(key)
          }
          currentData.form.serviceIds = serviceChoose.join(',')
          currentData.form.serviceChoose = serviceChoose
          currentData.members = [{merchantId: res.data.merchantId, merchantName: res.data.merchantName}]
          currentData.goodTypesTwo = [{productCategoryId: res.data.subCategoryId, name: res.data.subCategoryName}]
          currentData.brands = [{brandId: res.data.brandId, name: res.data.brandName}]
          loadTransport(res.data.merchantId)
        }
      })
    }
  }

  // 下一步
  function doNextStep() {
    formRef.value.validate((valid) => {
      if(valid) {
        saveOrUpdateGoodsBaseInfoApi(`${currentData.form.productId ? 'update' : 'save'}`, currentData.form).then(res => {
          if(res.code === '200') {
            if(!currentData.form.productId) {
              store.commit('productId', res.data)
            }
            window.sessionStorage.setItem('merchantId', currentData.form.merchantId)
            emits('nextStep')
          } else {
            currentThis.$message.error(res.message)
          }
        })
      }
    })
  }

  // 关闭
  function doClose() {
    emits('close')
  }

  // 获取厂商下拉列表数据
  function loadMembers(merchantName) {
    // if(!merchantName) {
    //   return
    // }
    // currentData.loading = true
    // getFactoryListApi({merchantName: merchantName}).then(res => {
    //   currentData.loading = false
    //   if(res.code === '200') {
    //     currentData.members = res.data
    //   }
    // })
  }

  /**
   * 查询商品分类下拉列表数据
   * parentId为0或不传时候，查询的是一级商品分类，其他情况查询是二级商品分类
   */
  function loadGoodsType(parentId) {
    if(parentId) {
      let chooseData = currentData.goodTypesOne.filter(item => {
        return item.productCategoryId === parentId
      })[0]
      currentData.form.parentCategoryName = chooseData.name
    } else {
      currentData.form.parentCategoryName = ''
    }
    getGoodsTypeListApi({parentId: parentId}).then(res => {
      if(res.code === '200') {
        if(parentId) {
          currentData.goodTypesTwo = res.data
          currentData.form.subCategoryId = ''
        } else {
          currentData.goodTypesOne = res.data
        }
      }
    })
  }
  // 商品二级分类选择改变时候执行
  function goodTypesTwoChange(id) {
    if(id) {
      let chooseData = currentData.goodTypesTwo.filter(item => {
        return item.productCategoryId === id
      })[0]
      currentData.form.subCategoryName = chooseData.name
    } else {
      currentData.form.subCategoryName = ''
    }
  }
  // 初始商品分类的一级分类
  loadGoodsType()

  // 初始化商品服务下拉数据
  loadGoodsService()
  function loadGoodsService() {
    getGoodsServiceListApi().then(res => {
      if(res.code === '200') {
        currentData.goodServices = res.data
      }
    })
  }
  // 商品服务选择改变时候触发
  function goodsServiceChange(e) {
    currentData.form.serviceIds = e.join(',')
  }

  // 获取运费模板下拉数据
  function loadTransport(merchantId) {
    if(!merchantId) {
      currentData.transports = []
      return 
    }
    getFreightTempListApi(merchantId).then(res => {
      if(res.code === '200') {
        currentData.transports = res.data
      }
    })
  }

  // 查询品牌下拉列表数据
  function loadBrands(brandName) {
    if(!brandName) {
      return
    }
    currentData.loading = true
    getBrandListApi({brandName: brandName}).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.brands = res.data
      }
    })
  }
  // 品牌改变时候执行
  function brandChange(id) {
    if(id) {
      let chooseData = currentData.brands.filter(item => {
        return item.brandId === id
      })[0]
      currentData.form.brandName = chooseData.name
    } else {
      currentData.form.brandName = ''
    }
  }

  // 初始化商品标签下拉数据
  // loadLabels()
  // function loadLabels() {
  //   getGoodsLabelListApi().then(res => {
  //     if(res.code === '200') {
  //       currentData.labelList = res.data
  //     } else {
  //       currentThis.$message.error(res.message)
  //     }
  //   })
  // }

  // 清除富文本编辑器
  function clearEditor() {
    editorRef.value.destroyEditor()
  }
</script>

<style lang="less" scoped>
.goodsBaseInfo{
  :deep(.el-card){
    margin-bottom: 15px;
    .el-card__header{
      display: flex;
      align-items: center;
      .el-icon{
        margin-right: 5px;
      }
    }
    .el-card__body{
      padding: 40px 40px 20px 0;
      .input-y{
        width: 80%;
      }
      .input-w{
        width: 250px;
      }
      .btns{
        display: flex;
        justify-content: center;
      }
    }
  }
}
</style>